package com.base.andlangcore.http.interceptor

import com.base.andlangcore.http.ApiClient
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 拦截请求后 重新指定请求地址host
 */
class UrlInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()

        val requestBuilder = request.newBuilder()
        val headerValues = request.headers("BaseUrl")

        if (headerValues.isNotEmpty()) {
            val headUrlKey = headerValues[0]
            var newBaseUrl: HttpUrl? = null
            newBaseUrl = when (headUrlKey) {
                "otherHost" -> ApiClient.APP_API_HOST.toHttpUrlOrNull()
                else -> ApiClient.APP_API_HOST.toHttpUrlOrNull()
            }
            val oldHttpUrl = request.url
            val newHttpUrl = oldHttpUrl.newBuilder()
                .scheme(newBaseUrl!!.scheme)
                .host(newBaseUrl.host)
                .port(newBaseUrl.port)
                .build()
            return chain.proceed(requestBuilder.url(newHttpUrl).build())
        } else {
            return chain.proceed(request)
        }

    }
}